//index.js
//获取应用实例
var app = getApp()

Page({
  data: {
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    isHide: false,
    goodsList: [],
    isNeedLogistics: 0, // 是否需要物流信息
    allGoodsPrice: 0,
    yunPrice: 0,
    allGoodsAndYunPrice: 0,
    goodsJsonStr: "",
    orderType: "", //订单类型，购物车下单或立即支付下单，默认是购物车，
    youhuijine: 0, //优惠券金额
    count: 0,
    productId: 0,
    remark: "",
    addressId: 0,
    pointNumber: 0,
    product_sku: null,
    point: 0,
    showSelectCoupon: false,
    pointInfo: {},
    cashCount: 0,
    curCoupon: null, // 当前选择使用的优惠券
    orderUser:{},
    orderbuytype:0, //购买方式 0.直接购买 1.加入云仓
    orderpaymtype:0//支付方式 
  },
  PointNumber: function(e) {
    var point = e.detail.value;
    if (point > this.data.pointInfo.Point) {
      wx.showModal({
        title: '提示',
        content: '您的优惠券',
        showCancel: false,
      })
      return;
    }
    if (point > this.data.pointInfo.UsePoint) {
      wx.showModal({
        title: '提示',
        content: '每天优惠券使用上限是' + this.data.pointInfo.UsePoint + "张",
        showCancel: false,
      })
      return;
    }
    var proportion = point / this.data.pointInfo.PointToCashRate;
    this.setData({
      cashCount: proportion
    })
  },
  onLoad: function(e) {
    var that = this;
    // 查看是否授权
    wx.getSetting({
      success: function (res) {
        if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: function (res) {
              // 用户已经授权过,不需要显示授权页面,所以不需要改变 isHide 的值
              // 根据自己的需求有其他操作再补充
              // 我这里实现的是在用户授权成功后，调用微信的 wx.login 接口，从而获取code

            }
          });
        } else {
          // 用户没有授权
          // 改变 isHide 的值，显示授权页面
          that.setData({
            isHide: true
          });
        }
      }
    });



    if (!e.buyAmount) {
      console.log(123);
      wx.request({
        url: 'https://rjgs.sz81jk.com/api/VYwbangAPI.ashx',
        method: "POST",
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        data: {
          "action": "getOrderProduct",
          "userid": wx.getStorageSync('userid')
        },
        dataType: "json",
        success: function(res) {
          console.log(res.data);
          var data = res.data[0];
          that.setData({
            goodsList: data.LineItems,
            allGoodsPrice: data.Total,
            allGoodsAndYunPrice: data.Total,
            point: data.GetPointNumber
          })
        }
      })
    } else {
      that.setData({
        count: e.buyAmount,
        productId: e.productId,
        product_sku: e.product_sku
      })
      wx.request({
        url: 'https://rjgs.sz81jk.com/api/VYwbangAPI.ashx',
        method: "POST",
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        data: {
          "action": "getOrderProduct",
          "userid": wx.getStorageSync('userid'),
          "productSku": e.product_sku,
          "buyAmount": e.buyAmount
        },
        dataType: "json",
        success: function(res) {
          var data = res.data[0];
          console.log(data);
          that.setData({
            goodsList: data.LineItems,
            allGoodsAndYunPrice: data.Total,
          })
        }
      })
    }
    wx.request({
      url: 'https://rjgs.sz81jk.com/api/VYwbangAPI.ashx',
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data: {
        "action": "getDefaultAddress",
        "userid": wx.getStorageSync('userid')
      },
      dataType: JSON,
      success: (res) => {
        if (res.data != "{}") {
          var datajson = JSON.parse(res.data);
          that.setData({
            curAddressData: datajson,
            addressId: datajson.ShippingId
          });
        } else {
          that.setData({
            curAddressData: null
          });
        }
      }
    })
    wx.request({
      url: 'https://rjgs.sz81jk.com/api/VYwbangAPI.ashx',
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data: {
        'action': 'GetPointCondition',
        'userid': wx.getStorageSync('userid')
      },
      dataType: 'json',
      success: function(res) {
        that.setData({
          'pointInfo': res.data
        })
      }
    })
    //显示收货地址标识
    that.setData({
      isNeedLogistics: 1,
    });

    wx.request({
      url: 'https://rjgs.sz81jk.com/api/VYwbangAPI.ashx',
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data: {
        'action': 'getOrderUserInfo',
        'userid': wx.getStorageSync('userid')
      },
      dataType: 'json',
      success: function (res) {
        if (!res.data.success) {
          var data = res.data[0];
        that.setData({
          'orderUser': data
        })
          console.log(data);
      }
      }
    })
  },
  onShow: function() {
    var id = this.data.id;
    var that = this;
    if (id > 0) {
      wx.request({
        url: 'https://rjgs.sz81jk.com/api/VYwbangAPI.ashx',
        method: 'Post',
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        data: {
          'action': 'getAddressById',
          'id': id
        },
        success: function(res) {
          that.setData({
            curAddressData: res.data,
            addressId: res.data.ShippingId
          })
        },
      })
    }
  },
  getDistrictId: function(obj, aaa) {
    if (!obj) {
      return "";
    }
    if (!aaa) {
      return "";
    }
    return aaa;
  },

  createOrder: function(e) {
    this.data.remark = e.detail.value.remark;
    this.data.pointNumber = e.detail.value.PointNumber;
    if (this.data.addressId > 0) {
      console.log(e.detail.value.PointNumber);
      if (e.detail.value.PointNumber == undefined) {
        this.data.pointNumber = 0;
      }
      wx.showLoading();
      var that = this;
      var data;
      var selectCoupon = "";
      var couponCode = "";
      if (that.data.product_sku == null) {
        data = {
          action: "Submmitorder",
          PointNumber: that.data.pointNumber,
          selectCouponValue: selectCoupon,
          Shippingcity: 560,
          shippingType: "包邮",
          paymentType: 88,
          couponCode: couponCode,
          redpagerid: 0,
          shippingId: that.data.addressId,
          shiptoDate: "时间不限",
          groupbuyId: 0,
          remark: that.data.remark,
          bargainDetialId: 0,
          limitedTimeDiscountId: 0,
          userid: wx.getStorageSync('userid'),
          orderbuytype: that.orderbuytype,
          useBalance: that.data.orderpaymtype
        }
      } else {
        data = {
          action: "Submmitorder",
          PointNumber: that.data.pointNumber,
          selectCouponValue: selectCoupon,
          Shippingcity: 560,
          shippingType: "包邮",
          paymentType: 88,
          couponCode: couponCode,
          redpagerid: 0,
          shippingId: that.data.addressId,
          productSku: that.data.product_sku,
          buyAmount: that.data.count,
          from: "signBuy",
          shiptoDate: "时间不限",
          groupbuyId: 0,
          remark: that.data.remark,
          bargainDetialId: 0,
          limitedTimeDiscountId: 0,
          userid: wx.getStorageSync('userid'),
          useBalance: that.data.orderpaymtype
        }
      }
      wx.request({
        url: 'https://rjgs.sz81jk.com/api/VshopProcess.ashx',
        method: "POST",
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        data: data,
        dataType: "json",
        success: function(res) {
          var json = res.data;
          if (res.data.Status == "OK") {
            wx.hideLoading();
            wx.showModal({
              title: '提示',
              content: '提交订单成功',
              showCancel: false,
              success: function() {
                if (that.orderpaymtype==88)
                {
                wx.request({
                  url: 'https://rjgs.sz81jk.com/api/VYwbangAPI.ashx',
                  method: 'Post',
                  header: {
                    "Content-Type": "application/x-www-form-urlencoded"
                  },
                  data: {
                    'action': 'GetPayJson',
                    'openId': json.OrderId,
                    'userid': wx.getStorageSync('userid')
                  },
                  dataType: JSON,
                  success: function(data) {
                    var datajson = JSON.parse(data.data);
                    wx.requestPayment({
                      timeStamp: datajson.timeStamp,
                      nonceStr: datajson.nonceStr,
                      package: datajson.package,
                      signType: datajson.signType,
                      paySign: datajson.paySign,
                      success: function(res) {
                        wx.request({
                          url: 'https://rjgs.sz81jk.com/api/VYwbangAPI.ashx',
                          method: 'Post',
                          header: {
                            "Content-Type": "application/x-www-form-urlencoded"
                          },
                          data: {
                            'action': 'UserPayOrder',
                            'openId': json.OrderId,
                          },
                          dataType: JSON,
                          success: function(res) {
                            console.log(res);
                          }
                        })
                      },
                      fail: function(res) {
                        wx.showModal({
                          title: '提示',
                          content: '已取消支付',
                          showCancel: false,
                          success: function() {
                            wx.navigateTo({
                              url: '../orderlist/orderlist',
                            })
                          }
                        })
                      }
                    })
                  }
                })
                }
              }
            })
          } else {
            console.log(json);
            wx.hideLoading();
            wx.showModal({
              title: '提示',
              content: json.ErrorMsg,
              showCancel: false
            })
          }
        }
      })
    }
    else{
      wx.showToast({
        title: '请添加收货地址',
        icon: 'none',
        duration: 2000
      })
    }
  },
  bindChangebuytype:function(e){
    var type = e.detail.value[0] ;
    this.setData({
       orderbuytype:type
    });
    console.log(this.data.orderbuytype);
  },
  bindChangepayment: function (e) {
    var type = e.detail.value[0];
    this.setData({
      orderpaymtype: type
    });
    console.log(this.data.orderpaymtype);
  },
  addAddress: function() {
    wx.navigateTo({
      url: "/pages/add_edit/add_edit?isOrder=true"
    })
  },
  selectAddress: function() {
    wx.navigateTo({
      url: "/pages/address/address"
    })
  },
  requestInfo: function () {
    var that = this;
    wx.request({
      url: 'https://rjgs.sz81jk.com/api/VYwbangAPI.ashx',
      method: 'Post',
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data: {
        'action': 'UpdateUserInfo',
        'openid': wx.getStorageSync('sessionId').openid,
        'userhead': that.data.userInfo.avatarUrl,
        'username': that.data.userInfo.nickName
      },
      dataType: "json",
      success: function (res) {
        console.log(res.data);
      }
    })
  },
  bindGetUserInfo: function (e) {
    if (e.detail.userInfo) {
      //用户按了允许授权按钮
      var that = this;
      // 获取到用户的信息了，打印到控制台上看下
      console.log("用户的信息如下：");
      console.log(e.detail.userInfo);
      //授权成功后,通过改变 isHide 的值，让实现页面显示出来，把授权页面隐藏起来
      app.globalData.userInfo = e.detail.userInfo
      that.setData({
        userInfo: e.detail.userInfo,
        isHide: false
      })
      console.log(e.detail.userInfo);
      that.requestInfo();
    } else {
      //用户按了拒绝按钮
      wx.showModal({
        title: '警告',
        content: '您点击了拒绝授权，将无法进入订单购买，请授权之后再进入!!!',
        showCancel: false,
        confirmText: '返回授权',
        success: function (res) {
          // 用户没有授权成功，不需要改变 isHide 的值
          if (res.confirm) {
            console.log('用户点击了“返回授权”');
          }
        }
      });
    }
  }
  
})